package com.csinc.generate.core;

import com.csinc.generate.core.database.ConnectionUtil;
import com.csinc.generate.core.database.read.ReadTableFactory;
import com.csinc.generate.core.make.IMakeFactory;
import com.csinc.generate.core.base.model.GenBeanEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

/**
 * Create By 郭金宝 on 2018/7/23.<br>
 */
@Slf4j
public class CodeGenUtil {
    /**
     * 生产代码
     */
    public static List<String> codeGen(CodeGenModel model) {
        try {
            model.getGenerationEntity().setDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm"));
            log.info("---------------Step 1 初始化数据库连接---------------");
            ConnectionUtil.init(ReadTableFactory.getDeiver(model.getDbType()), model.getUrl(), model.getUsername(), model.getPasswd());
            log.info("---------------Step 2 读取数据源列表---------------");
            GenBeanEntity tableEntity = ReadTableFactory.getReadTable(model.getDbType()).read(model.getDbName(), model.getTableName());
            log.info("---------------Step 3 解析模板,生产代码---------------");
            return IMakeFactory.getMake(model.getParseType()).make(model.getGenerationEntity(), tableEntity, model.getFileList());
        } finally {
            ConnectionUtil.close();
        }
    }
    /**
     * 生产代码
     */
    public static List<String> makeGen(CodeGenModel model) {
        try {
            model.getGenerationEntity().setDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm"));
            log.info("---------------Step 1 初始化数据库连接---------------");
            ConnectionUtil.init(ReadTableFactory.getDeiver(model.getDbType()), model.getUrl(), model.getUsername(), model.getPasswd());
            log.info("---------------Step 2 读取数据源列表---------------");
            GenBeanEntity tableEntity = ReadTableFactory.getReadTable(model.getDbType()).read(model.getDbName(), model.getTableName());
            log.info("---------------Step 3 解析模板,生产代码---------------");
            return IMakeFactory.getMake(model.getParseType()).makeByTemplateModel(model.getGenerationEntity(), tableEntity, model.getListTemplateModel());
        } finally {
            ConnectionUtil.close();
        }
    }
    /**
     * 获取数据库信息
     */
    public static GenBeanEntity getTableBean(CodeGenModel model) {
        try {
            //Step 1 初始化数据库连接
            ConnectionUtil.init(ReadTableFactory.getDeiver(model.getDbType()), model.getUrl(), model.getUsername(), model.getPasswd());
            //Step 2 读取数据源列表
            GenBeanEntity tableEntity = ReadTableFactory.getReadTable(model.getDbType()).read(model.getDbName(), model.getTableName());
            return tableEntity;
        } finally {
            ConnectionUtil.close();
        }
    }
}
